/*
 * @Author: 菜鸟裹裹 675687356@qq.com
 * @Date: 2025-06-10 09:27:22
 * @LastEditors: 菜鸟裹裹 675687356@qq.com
 * @LastEditTime: 2025-06-16 14:14:43
 * @FilePath: /customer-service-web/src/store/modules/user.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { getUserInfo, login } from '@/api/sys'
import { getItem, setItem, removeAllItem } from '@/utils/storage'
import { TOKEN } from '@/constant'
import { setTimeStamp } from '@/utils/auth'
import router, { resetRouter } from '@/router'
export default {
  namespaced: true,
  state: () => ({
    token: getItem(TOKEN) || '',
    userInfo: {}
  }),
  mutations: {
    setToken(state, token) {
      state.token = token
      setItem(TOKEN, token)
    },
    setUserInfo(state, userinfo) {
      state.userInfo = userinfo
    }
  },
  actions: {
    /**
     * 登录请求动作
     * @param context
     * @param userInfo
     * @returns {Promise<unknown>}
     */
    // login(context, userInfo) {
      
    //   const { username, password } = userInfo
    //   return new Promise((resolve, reject) => {
    //     console.log(userInfo,"userInfouserInfouserInfo===");
    //     login({
    //       username: username,
    //       password: password
    //     }).then(data => {
    //       context.commit('user/setToken', data.token)
    //       // 保存登录时间
    //       setTimeStamp()
    //       resolve()
    //     }).catch(err => {
    //       reject(err)
    //     })
    //   })
    // },
    login({ commit }, userInfo) {
      const { username, password } = userInfo;
      return login({ username, password })
        .then(data => {
          commit('setToken', data.token);
          setTimeStamp();
          return data; // 可选：返回数据给调用者
        })
        .catch(err => {
          console.error('登录失败', err);
          throw err; // 重新抛出错误，让调用者处理
        });
    },
    async getUserInfo(context, data) {
      const res = await getUserInfo()
      this.commit('user/setUserInfo', res)
      return res
    },
    logout() {
      resetRouter()
      this.commit('user/setToken', '')
      this.commit('user/setUserInfo', {})
      removeAllItem()
      router.push('/login')
    },
    resetToken() {
      return new Promise(resolve => {
        this.commit('user/setToken', '')
        this.commit('user/setUserInfo', [])
        removeAllItem()
        router.push('/login')
      })
    }
  }
}
